//
//  JYTabBar.swift
//  01.weibo
//
// 温馨提示:  如果单单写一个类出来不做任何操作是不会进入类中的方法的
//

import UIKit

class JYTabBar: UITabBar {

    //定义闭包 (因为在构造函数时,没有初始化会报错,所以要定义为可选)
    var composeClosure: (() ->())?
    override func layoutSubviews() {
        super.layoutSubviews()
        let width = frame.size.width/CGFloat(JYTabBarButtonCount)
        var index = 0
        //遍历UITabBarButton,并设置frame
        for subview in subviews {
            
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!){
            subview.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: frame.size.height)
            
            index++
            if index == 2 {
            index++
            }
        }
    }
        composeButton.frame = CGRect(x: CGFloat(2) * width, y: 0, width: width, height: frame.size.height)
        
    }
    // Mark - 点击事件 View 弹不出另外的控制器,点击事件需要告诉外面的控制器
     // @objc: 让OC可以调用我们swift的方法,系统默认会为所有的swift方法加上@objc,如果方法加了private,就不会帮我们加@objc
    @objc private func didClickComposeButton () {
        //调用闭包
        composeClosure?()
    }

    //懒加载 + 号按钮
    private lazy var composeButton: UIButton = {
    
        let button = UIButton()
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Selected)
        //添加点击事件
        button.addTarget(self, action: Selector("didClickComposeButton"), forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(button)
        
        return button
    }()
    
}
